package com.rogerfan.easy.shiro;

import java.util.concurrent.TimeUnit;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import com.rogerfan.easy.common.IdFactory;
import com.rogerfan.easy.web.util.WebUtil;

@Component
public class ShiroTokenManager {
	
	public static String HEADER_TOKEN_NAME="SHIRO-APP-TOKEN";
	@Autowired
	private StringRedisTemplate redisTemplate;
	
	
	public String sessionKey(ServletRequest req){
		HttpServletRequest _req = (HttpServletRequest)req;
		String tokenValue=WebUtil.getHeader(_req, HEADER_TOKEN_NAME);
		if(StringUtils.isNotBlank(tokenValue)){
			return redisTemplate.opsForValue().get( tokenValue);
		}
		return null;
	}
	
	
	public String saveToken(String sessionId){
		String token =IdFactory.getRandomSerialNumber();
		redisTemplate.opsForValue().set( token, sessionId,30*60,TimeUnit.SECONDS);
		return token;
	}
	
	public void remove(String sessionId){
		redisTemplate.delete(sessionId);
	}

}
